/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wii.elpro.web.action;

import com.wii.elpro.dao.hb.PriceDAOImpl;
import com.wii.elpro.dao.hb.ProdukDAOImpl;
import com.wii.elpro.entity.Produk;
import com.wii.elpro.entity.ProdukMaterial;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.ProductNewForm;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author Vyor
 */
public class ProductSaveAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        ProductNewForm produkNewForm = (ProductNewForm) form;
        Produk p = new Produk();
        p.setKode(produkNewForm.getKode());
        p.setNama(produkNewForm.getNama());
        p.setWeight(produkNewForm.getWeight());
        p.setStockLI(produkNewForm.getStockLI());
        p.setStockLE(produkNewForm.getStockLE());
        p.setProdukMaterials(new ArrayList<ProdukMaterial>());
        p.setHargaHpp(new PriceDAOImpl().getPrice(Long.parseLong(request.getParameter("idHargaHpp"))));
        ActionMessages messages = new ActionMessages();        
        String fw = request.getParameter("submit");
        try {
            new ProdukDAOImpl().save(p);
            messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully saved."));
            saveMessages(sess, messages);
            forward = fw;
        }catch(Exception ex){
            messages.add("message", new ActionMessage("customMessage", "Application is fail to save your data. Please contact my developer."));
            saveMessages(sess, messages);
            forward = "fail";
            ex.printStackTrace();
        }
        return mapping.findForward(forward);
    }
}
